package com.example.demo.controller;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/get")
    @Cacheable(value = "spring.cache", key = "#id+#username")
    public String get(String username, String id) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(id)) {
            return "参数错误";
        }
        System.out.println("执行了 get 方法");
        return "欢迎回来:" + username + "!";
    }

    @CachePut(value = "spring.cache", key = "#id+#username")
    @RequestMapping("/put")
    public String put(String username, String id) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(id)) {
            return "参数错误";
        }
        System.out.println("执行了 put 方法");
        return "更新了用户:" + username + "~";
    }

    @CacheEvict(value = "spring.cache", key = "#id+#username")
    @RequestMapping("/del")
    public String del(String id, String username) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(id)) {
            return "参数错误";
        }
        System.out.println("清除缓存");
        return "清除用户 "+ username +" 缓存!";
    }

}
